package com.wsl.configuration;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
public class DataConfiguration {
    @Bean
    public DataSource createDataSource() throws SQLException {
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        //配置主库
        BasicDataSource masterDataSource = new BasicDataSource();
        masterDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        masterDataSource.setUrl("jdbc:mysql://localhost:3306/master?serverTimezone=UTC");
        masterDataSource.setUsername("root");
        masterDataSource.setPassword("qwer1234");
        dataSourceMap.put("master", masterDataSource);
        //配置第一个从库
        BasicDataSource slaveDataSource = new BasicDataSource();
        slaveDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        slaveDataSource.setUrl("jdbc:mysql://localhost:3306/salve0?serverTimezone=UTC");
        slaveDataSource.setUsername("root");
        slaveDataSource.setPassword("qwer1234");
        dataSourceMap.put("master", slaveDataSource);
        //配置第二个从库
        BasicDataSource slaveDataSource1 = new BasicDataSource();
        slaveDataSource1.setDriverClassName("com.mysql.jdbc.Driver");
        slaveDataSource1.setUrl("jdbc:mysql://localhost:3306/salve1?serverTimezone=UTC");
        slaveDataSource1.setUsername("root");
        slaveDataSource1.setPassword("qwer1234");
        dataSourceMap.put("master", slaveDataSource1);

        //配置读写分离规则
        MasterSlaveRuleConfiguration masterSlaveRuleConfiguration =
                new MasterSlaveRuleConfiguration("master_salve", "master", Arrays.asList("salve0", "salve1"));

        //获取数据源对象
        DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, masterSlaveRuleConfiguration, new Properties());

        return dataSource;


    }
}
